package com.eroad.product.tools;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;

import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.utils.CommonUtils;
import com.example.xf.DownloadInterface;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * <p><b>Title：</b> App自动更新通知栏下载</p>
 * <p><b>Description：</b> </p>
 *
 * @author tangxin
 * @date 2016年12月6日 下午4:17:32
 */
public class UpdateAppService extends Service {
    private Context context;
    private Notification notification;
    private NotificationManager nManager;
    private PendingIntent pendingIntent;
    private RemoteViews contentView;
    private int length;
    private int downnum = 0;// 已下载的大小
    protected static SharedPreferences preferences;
    protected SharedPreferences.Editor editor;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        context = getApplicationContext();
        preferences = getSharedPreferences("User_preservation", Context.MODE_PRIVATE);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        downnum = 0;
        CreateInform();
        setParam("Check_and_update", "1");
        return super.onStartCommand(intent, flags, startId);
    }

    public void setParam(String key, String val) {
        editor = preferences.edit();
        editor.putString(key, val);
        // 提交数据
        editor.commit();
    }

    public String getParam(String key, String def) {
        return preferences.getString(key, def);
    }

    @Override
    public void onDestroy() {
        setParam("Check_and_update", "0");
        super.onDestroy();
    }

    // 创建通知
    public void CreateInform() {
        // 定义一个PendingIntent，当用户点击通知时，跳转到某个Activity(也可以发送广播等)

        // 创建一个通知
        notification = new Notification();
        notification.icon = R.drawable.logo180;
        notification.tickerText = "开始下载~~";
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        // 用NotificationManager的notify方法通知用户生成标题栏消息通知
        nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        // 如果拥有相同id的通知已经被提交而且没有被移除，该方法会用更新的信息来替换之前的通知。

        contentView = new RemoteViews(getPackageName(), R.layout.news_eerr);
        contentView.setImageViewResource(R.id.image, R.drawable.logo180);
        // contentView.setTextViewText(R.id.name, "vgo.apk");
        contentView.setTextViewText(R.id.tv_progress, "已下载了0%");
        contentView.setProgressBar(R.id.progressbar, 100, 0, true);

        notification.contentView = contentView;

        nManager.notify(100, notification);// id是应用中通知的唯一标识

        new Thread(new updateRunnable()).start();// 这个是下载的重点，是下载的过程
    }

    class updateRunnable implements Runnable {
        @Override
        public void run() {
            try {
                if (!TextUtils.isEmpty(getParam("UpdateApp_url", ""))) {
                    DownLoadApp(getParam("UpdateApp_url", ""));
                } else {
                    DownLoadApp(EmmApplication.DownLoadingUrl);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @SuppressLint("ShowToast")
        public void DownLoadApp(String urlString) throws Exception {
            URL url = new URL(urlString);
            Log.v("DownLoad  urlString", urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            length = urlConnection.getContentLength();
            InputStream inputStream = urlConnection.getInputStream();
            OutputStream outputStream = new FileOutputStream(getFile());

            byte buffer[] = new byte[1024 * 3];
            int readsize = 0;
            while ((readsize = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, readsize);
                downnum += readsize;
                if (downnum < length) {
                    contentView.setTextViewText(R.id.tv_progress, "已下载了" + (int) downnum * 100 / length + "%");
                    contentView.setProgressBar(R.id.progressbar, 100, (int) downnum * 100 / length, false);
                    nManager.notify(100, notification);
                }
                if (downnum >= length) {

                    EmmApplication.IsUpdate = true;
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(getFileUri(),"application/vnd.android.package-archive");

                    pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

                    contentView = new RemoteViews(getPackageName(), R.layout.news_eerr);
                    contentView.setImageViewResource(R.id.image, R.drawable.logo180);
                    contentView.setTextViewText(R.id.tv_progress, "已经下载成功、点击安装");
                    contentView.setProgressBar(R.id.progressbar, 100, (int) downnum * 100 / length, false);
                    notification.contentView = contentView;
                    notification.contentIntent = pendingIntent;
                    nManager.notify(100, notification);
                    handler.sendEmptyMessage(1);
                }
                if (null != DownloadInterface.downloads) {
                    DownloadInterface.downloads.progress(downnum, length);
                }
            }
            inputStream.close();
            outputStream.close();
        }

        @SuppressLint("HandlerLeak")
        Handler handler = new Handler() {

            public void handleMessage(android.os.Message msg) {
                if (msg.what == 1) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
                    try {
                        intent.setDataAndType(getFileUri(),"application/vnd.android.package-archive");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    downnum = 0;
                    setParam("Check_and_update", "0");
                    startActivity(intent);
                }

            }
        };

        public Uri getFileUri() throws Exception {
            return getFileUri(getFile());
        }

        public Uri getFileUri(File file) {
            Uri uri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(context,"com.emm.yixun.mobile.fileprovider", file);
            } else {
                uri = Uri.fromFile(file);
            }
            return uri;
        }

        // 获取文件的保存路径
        public File getFile() throws Exception {
            String SavePath = getSDCardPath() + "/xinfang/app";
            File path = new File(SavePath);
            File file = new File(SavePath + "/emm.apk");
            if (!path.exists()) {
                path.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            return file;
        }

        // 获取SDCard的目录路径功能
        private String getSDCardPath() {
            File sdcardDir = null;
            // 判断SDCard是否存在
            boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
            if (sdcardExist) {
                sdcardDir = Environment.getExternalStorageDirectory();
            }
            return sdcardDir.toString();
        }
    }
}